package top.byfree.jbyan.saber.controller

import cn.dev33.satoken.annotation.SaCheckPermission
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import top.byfree.jbyan.saber.bean.dto.FilterPermDto
import top.byfree.jbyan.saber.bean.dto.PermDto
import top.byfree.jbyan.saber.common.AddGroup
import top.byfree.jbyan.saber.common.UpdateGroup
import top.byfree.jbyan.saber.common.ok
import top.byfree.jbyan.saber.common.result
import top.byfree.jbyan.saber.exception.SaberServiceException
import top.byfree.jbyan.saber.service.PermService

/**
 * 权限控制器
 *
 * @author jbyan
 * @since 27/3/2024
 */
@RestController
@RequestMapping("perm")
class PermController(
    @Autowired private val permService: PermService
) {

    /**
     * 根据权限编号获取权限详细信息
     *
     * @param permId 角色编号
     */
    @GetMapping("{permId}")
    @SaCheckPermission("admin.perm.cat")
    fun get(@PathVariable permId: String) =
        permService.getOne(permId)?.let { ok(data = it) } ?: throw SaberServiceException("获取权限编号不存在")

    /**
     * 分页条件获取权限列表
     *
     * @param size 每页数据个数
     * @param current 当前业
     */
    @PostMapping("page/{size}/{current}")
    @SaCheckPermission("admin.perm.cat")
    fun page(
        @PathVariable size: Int,
        @PathVariable current: Int,
        @RequestBody filterPermDto: FilterPermDto
    ) = ok(data = permService.page(size, current, filterPermDto))

    /**
     * 新增权限
     *
     * @param permDto 新增权限请求体
     */
    @PutMapping
    @SaCheckPermission("admin.perm.add")
    fun add(@Validated(AddGroup::class) @RequestBody permDto: PermDto) = result(permService.add(permDto))

    /**
     * 更新权限信息
     *
     * @param permId 权限编号
     * @param permDto 权限请求体
     */
    @PostMapping("{permId}")
    @SaCheckPermission("admin.perm.update")
    fun update(
        @PathVariable permId: String,
        @Validated(UpdateGroup::class) @RequestBody permDto: PermDto
    ) = result(permService.update(permId, permDto))


    /**
     * 逻辑删除权限信息
     *
     * @param permId 权限编号
     */
    @DeleteMapping("{permId}")
    @SaCheckPermission("admin.perm.delete")
    fun delete(
        @PathVariable permId: String
    ) = result(permService.delete(permId))
}